package cn.usbtg.sutil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * util:file
 */
public final class FileUtil {

    /**
     * 获取文件后缀名
     *
     * @param file
     * @return
     */
    public static String getSuffix(File file) {
        String fileName = file.getName();
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 拷贝文件
     *
     * @param file
     * @param copyFile
     */
    public static void copyTo(File file, File copyFile) {
        try {
            if (!file.exists()) {
                throw new RuntimeException("file not exists," + file.getPath());
            }

            File copyDir = copyFile.getParentFile();
            if (!copyDir.exists() || !copyDir.isDirectory()) {
                boolean isSuccess = copyDir.mkdirs();
                if (!isSuccess) {
                    throw new RuntimeException("directory does not exist and create the failure," + copyDir.getCanonicalPath());
                }
            }

            FileInputStream in = new FileInputStream(file);
            FileOutputStream out = new FileOutputStream(copyFile);
            byte[] buffer = new byte[1024];
            int ins;
            while ((ins = in.read(buffer)) != -1) {
                out.write(buffer, 0, ins);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}